var textLayer;
var recordFlag:Boolean;
var micStatus:String;
var onceFlag:Boolean;
// var recordedFlag:Boolean;
var collabResult:Boolean;

function init(param, data, slot)
{
	Packages.model.Context.activeContent=this;

	/*// Condition.check
	if (Packages.model.UserProfile.RecordingCollabId==null) 
	{
		Packages.components.SceneAgent.loadScene("content/HomePage", true);
		return;
	}
	// */
	
	// UI.init
	var basic=Packages.system.mlf.GateKeeper.scanElement(this._name, "basic");
	Packages.system.display.JAccordion.initialize(basic);
	
	// Render.init
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "onairTitle"));
	Packages.system.render.Filter.titleFilter(Packages.system.mlf.GateKeeper.scanElement(this._name, "myReadjoyTitle"));
	Packages.system.display.SceneTransition.rollOut();

	// Event.init
	var evtTargetArr:Array=new Array();
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "Prepairation_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "OnAir_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "PostProduction_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "Publish_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "back_print"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "sendMsgSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "prevBlockSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "nextBlockSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "taskOperSpot"));
	evtTargetArr.push(Packages.system.mlf.GateKeeper.scanElement(this._name, "switchInfoSpot"));
	Packages.system.events.StateFulButtonEvent.initialize(evtTargetArr);

	invokeInitComplete();
}

function dispose()
{
	Packages.system.mlf.GateKeeper.removeListener("onReleaseButtonEvent", this);
	Packages.system.mlf.GateKeeper.removeListener("onLadderChange", this);
	Packages.system.mlf.GateKeeper.removeListener("onMicStatus", this);

	Packages.system.mlf.GateKeeper.removeListener("onSceneTransitionComplete", this);	//

	delete textLayer;
	delete recordFlag;
	delete micStatus;
	delete onceFlag;
	// delete recordedFlag;
	delete collabResult;
	
	Packages.modula.RTxtReader.removeInstance();
	// remove mic status listener
	var active_mic:Microphone=Microphone.get();
	active_mic.onActivity=null;

	Packages.modula.MicrophoneDevice.close();

	// Packages.modula.task.Common.stopCollabEnvironment();
}

function invokeInitComplete()
{
	Packages.system.mlf.GateKeeper.addListener("onReleaseButtonEvent", this);
	Packages.system.mlf.GateKeeper.addListener("onLadderChange", this);
	Packages.system.mlf.GateKeeper.addListener("onMicStatus", this);

	Packages.system.mlf.GateKeeper.addListener("onSceneTransitionComplete", this);

	// check the collab env and initialize the env
	collabResult=Packages.modula.task.Common.checkCollabEnvironment(this._name);
	
	if (Packages.model.UserProfile.recordingCollabFlag)
	{
		if (Packages.modula.task.Composition.host)
		{
			Packages.log(Packages.model.UserProfile.data.nickName+".update setDefaultPoint", "info");
			Packages.modula.task.Common.updateCollab(this, "setDefaultPoint", null);
		}
	}
	else 
	{
		setDefaultPoint();
	}

	initTxtReader();

	// flag initialize
	// recordedFlag=false;
	onceFlag=false;
	micStatus="silence";
	Packages.modula.task.Processor.clear();

	recordFlag=false;

}

function onSceneTransitionComplete(evt:Object)
{
	Packages.system.mlf.GateKeeper.removeListener("onSceneTransitionComplete", this);
	if (collabResult)
	{
		switchInfo();
	}
}

function setDefaultPoint()
{
	// select the default startPoint from blank/save/active by condition
	Packages.log(Packages.model.UserProfile.data.nickName+".in setDefaultPoint", "info");

	var selectedPointSpot=Packages.system.mlf.GateKeeper.scanElement(this._name, "blankPointSpot");
	var param=mlf.mcmanager.PathResolver.drawPath(selectedPointSpot);
	var data:Object=new Object();
	data.execFlag=true;
	Packages.system.events.StateFulButtonEvent.invokeReleaseEvent(param, data, this._name);
}

function initTxtReader()
{
	var portlet=mlf.gatekeeper.native.Caller.scanElement(this._name, "txtReader");
	Packages.modula.RTxtReader.getInstance(portlet);

	Packages.modula.RTxtReader.displayBlockProgress(this._name);
}

function nextBlock(preOffsetFlag:Boolean)
{
	if (recordFlag) 
	{	
		if (onceFlag) Packages.modula.RTxtReader.switchBlock(1, true, preOffsetFlag);
		else 
		{
			onceFlag=true;
			Packages.modula.RTxtReader.switchBlock(-2, true);
		}
		micStatus="active";
		activate();
	}
	else Packages.modula.RTxtReader.switchBlock(1, recordFlag);
}

function prevBlock()
{
	if (recordFlag)		
	{
		Packages.modula.RTxtReader.switchBlock(-1, true);
		micStatus="active";
		activate();
	}
	else Packages.modula.RTxtReader.switchBlock(-1, recordFlag);
}

function start(owner:String)
{
	// permission -> operation -> status -> appearance
	// permission and operation
	var rst:Boolean=Packages.modula.task.Processor.record(!recordFlag, owner);
	if (!rst) return;
	else Packages.modula.MessageCenter.send(owner+" {RECORDING_OPERATION} "+!recordFlag, 1, 0);
	
	recordFlag=!recordFlag;

	// addMicrophoneActivityEventListener (filtered by MicrophoneDevice)
	// silence, active
	var taskOperLabel_tf=Packages.system.mlf.GateKeeper.scanElement(this._name, "taskOperLabel");
	if (recordFlag)
	{
		taskOperLabel_tf.htmlText=Packages.system.mlf.GateKeeper.scanDictionary(taskOperLabel_tf, "TaskOperLabel_CLOSE");
	}
	else taskOperLabel_tf.htmlText=Packages.system.mlf.GateKeeper.scanDictionary(taskOperLabel_tf, "TaskOperLabel_OPEN");
	
	if (recordFlag)
	{
		// set textLayer
		var portlet=mlf.gatekeeper.native.Caller.scanElement(this._name, "txtReader");
		textLayer=portlet.filling_rect.textLayer;
		// publish and first block
		microphoneStatus("active");
		// nextBlock();
		// recordedFlag=true;
	}
	else 
	{
		micStatus="silence";
	}
}

function onMicStatus(evt:Object)
{
	microphoneStatus(evt.param);
}

function microphoneStatus(param)
{
	if (!recordFlag) return;
	if (param.indexOf("silence")>-1)
	{
		// silence status
		if (micStatus=="active")	// "active" means the voice launched
		{
			// check progress threshold
			if (overGap()) 
			{
				micStatus="silence";	// "silence" means the voice end
				silence();
			}
		}
	}
	else if (param.indexOf("active")>-1)
	{
		// active status
		if (micStatus=="silence")
		{
			// auto change
			micStatus="active";
			activate();
			// 2008-11-21 collab resume recording, not change block
			// 2008-11-23 first block
			if (Packages.model.UserProfile.recordingCollabFlag)
			{
				// true or not
				if (!onceFlag) nextBlock();
			}
			else nextBlock(true);	//
		}
	}
	// trace("micStatus: "+micStatus);
}

function overGap():Boolean
{
	if (textLayer.textColor==0x000000)
	{
		return true;
	}
	else return false;
}

function silence()
{
	var ladder=mlf.gatekeeper.native.Caller.scanElement(this._name, "aladder");
	ladder._visible=false;
}

function activate()
{
	var ladder=mlf.gatekeeper.native.Caller.scanElement(this._name, "aladder");
	ladder._visible=true;
}

function onLadderChange(evt:Object)
{
	var ladder=mlf.gatekeeper.native.Caller.scanElement(this._name, "aladder");
	ladder.jnladder.pos=evt.param;
	ladder.jnladder.draw();
}

function setBlankRecordingPoint()
{
	Packages.log("setBlankRecordingPoint", "debug");
	// start new recording
	
	Packages.modula.task.Composition.audioId=null;
	Packages.modula.task.Composition.syncId=null;
	Packages.modula.task.Composition.processData=new Object();

	Packages.modula.RTxtReader.switchBlock(-2);
	Packages.modula.task.Common.establishAudioChannel();
}

function setSaveRecordingPoint()
{
	Packages.log("setSaveRecordingPoint", "debug");
	// go on recording from the task-saving point
	if (Packages.modula.task.Composition.latestAudio==null)
	{
		Packages.modula.MessageCenter.send("NO_SAVE_POINT", 1, 0);
		return;
	}
	Packages.modula.task.Composition.audioId=Packages.modula.task.Composition.latestAudio.uuid;
	Packages.modula.task.Composition.flvAudioId=Packages.modula.task.Composition.latestAudio.audioId;	// flvAudioId or audioId
	Packages.modula.task.Composition.syncId=Packages.modula.task.Composition.latestAudio["sync.syncId"];
	Packages.modula.task.Composition.processData={duration:Packages.modula.task.Composition.latestSyncFile.duration, timestamp:Packages.modula.task.Composition.latestSyncFile.point};

	Packages.log("audioId: "+Packages.modula.task.Composition.audioId, "debug");
	Packages.log("flvAudioId: "+Packages.modula.task.Composition.flvAudioId, "debug");
	Packages.log("syncId: "+Packages.modula.task.Composition.syncId, "debug");
	Packages.log("duration: "+Packages.modula.task.Composition.latestSyncFile.duration, "debug");
	Packages.log("timestamp: "+Packages.modula.task.Composition.latestSyncFile.point, "debug");

	Packages.modula.task.Processor.initializeTimestamp();

	Packages.modula.RTxtReader.switchBlock(Packages.modula.task.Composition.latestSyncFile.point.length-1);

	onceFlag=true;
}

function setActiveRecordingPoint()
{
	Packages.log("setActiveRecordingPoint", "debug");
	// go on recording
}

function switchInfo()
{
	var hintDisplayContainer=Packages.system.mlf.GateKeeper.scanElement(this._name, "hintDisplayContainer");
	if (hintDisplayContainer._visible)
	{
		Packages.system.mlf.GateKeeper.updatePortletView(this._name, "hintDisplayContainer", "infoDisplayContainer");
	}
	else Packages.system.mlf.GateKeeper.updatePortletView(this._name, "infoDisplayContainer", "hintDisplayContainer");
}

function onReleaseButtonEvent(evt:Object, execFlag:Boolean)
{
	Packages.log(Packages.model.UserProfile.data.nickName+".in onReleaseButtonEvent "+execFlag+" "+Packages.model.UserProfile.recordingCollabFlag+" "+evt.data.execFlag, "info");

	// Three types operation for collab env
	// private operation: sendMsgSpot(public), switchInfoSpot, print(host)
	// public operation: prevBlockSpot, nextBlockSpot, taskOperSpot
	// host operation: PointSpot

	// here's the no collab event, private operation
	if (evt.param=="sendMsgSpot" || evt.param=="switchInfoSpot" || evt.param.indexOf("print")>-1)
	{
		evt.data=new Object();
		evt.data.execFlag=true;
	}
	
	// collab operation and collab event in turn
	if (!evt.data.execFlag && Packages.model.UserProfile.recordingCollabFlag && !execFlag)
	{
		// collab operation broadcast
		// host operation restriction
		if (evt.param.indexOf("PointSpot")>-1)
		{
			if (!Packages.modula.task.Composition.host)
			{
				Packages.modula.MessageCenter.send("YOU_HAVE_NO_RIGHTS_TO_DO_HOST_OPERATION", 1, 0);
				return;
			}
		}

		if (evt.param=="taskOperSpot")
		{
			if (Packages.modula.task.Composition.speakerHolder!=Packages.model.UserProfile.data.nickName && recordFlag)
			{
				Packages.modula.MessageCenter.send("YOU_ARE_NOT_THE_SPEAKERHOLDER", 1, 0);
				return;
			}
		}

		evt.owner=Packages.model.UserProfile.data.nickName;
		var args=new Array();
		args.push(evt);
		args.push(true);
		Packages.modula.task.Common.updateCollab(this, "onReleaseButtonEvent", args);

		return;
	}

	// attached information feedback in collab event
	if (execFlag && Packages.model.UserProfile.recordingCollabFlag && Packages.modula.task.Composition.host) //
	{
		// if host got the collab event, broadcast the info to collabMembers 
		// and collabMembers could check the operation mentioned by the host
		// @add feedback of the operation in the MessageCenter
		// Packages.modula.task.Common.sendMsg(evt.param.toUpperCase());
	}
	
	if (evt.param=="prevBlockSpot")
	{
		prevBlock();
	}
	else if (evt.param=="nextBlockSpot")
	{
		nextBlock();
	}
	else if (evt.param=="taskOperSpot")
	{
		start(evt.owner);
	}
	else if (evt.param=="sendMsgSpot")
	{
		Packages.modula.task.Common.sendMsg();
	}
	else if (evt.param=="switchInfoSpot")
	{
		switchInfo();
	}
	else if (evt.param=="blankPointSpot")
	{
		setBlankRecordingPoint();
	}
	else if (evt.param=="savePointSpot")
	{
		setSaveRecordingPoint();
	}
	else if (evt.param=="activePointSpot")
	{
		setActiveRecordingPoint();
	}
	else if (evt.param.indexOf("print")>-1)
	{
		if (Packages.model.UserProfile.recordingCollabFlag && !Packages.modula.task.Composition.host)
		{
			Packages.modula.MessageCenter.send("YOU_HAVE_NO_RIGHTS_TO_DO_HOST_OPERATION", 1, 0);
			return;
		}

		var printName=evt.param.substr(0, evt.param.length-6);
		Packages.modula.task.Common.switchRoom(printName, this._name);
	}
}